package org.water.garden.receiver;

import java.util.Map;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentReceiver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.Im.Provider;
import android.provider.Im.ProviderSettings;
import android.provider.MediaStore.Images;
import android.util.Log;

public abstract class SetupProviderReceiver extends IntentReceiver {
	
	protected Context context;
	
	private final static String LOG_TAG = "SetupProviderReceiver";
	
	@Override
	public void onReceiveIntent(Context context, Intent intent) {
		this.context = context;
		Log.i(LOG_TAG, "Start Setup Provider " + getProviderName());
		
		Cursor cur = context.getContentResolver().query(Provider.CONTENT_URI, 
				new String[]{Provider._ID, Provider.NAME}, Provider.NAME+"=?", 
				new String[]{getProviderName()}, null);
		Uri pUri = Provider.CONTENT_URI;
		long providerId;
		if(!cur.first()){
			pUri = context.getContentResolver().insert(Provider.CONTENT_URI, getProviderValues());	
			Log.i(LOG_TAG, "Insert Provider Value Uri:" + pUri);
			providerId = ContentUris.parseId(pUri);
			
			Map<String, Object> settings = getProviderSettings();
			if(settings != null && settings.size() > 0){
				for (Map.Entry<String, Object> setting : settings.entrySet()) {
					ContentValues v = new ContentValues(3);
		            v.put("provider", Long.valueOf(providerId));
		            v.put("name", setting.getKey());
		            v.put("value", setting.getValue().toString());
					context.getContentResolver().insert(ProviderSettings.CONTENT_URI, v);
				}
			}
		}else{
			providerId = cur.getLong(0);
			pUri = ContentUris.withAppendedId(Provider.CONTENT_URI, providerId);
			Log.i(LOG_TAG, "Provider Uri:" + pUri);
		}
		cur.close();
		
		String iconValue = ProviderSettings.getStringValue(context.getContentResolver(), providerId, "icon");
		if(iconValue == null){
			String iconUri = Images.Media.insertImage(context.getContentResolver(), getProviderTitleIcon(), "garden_provider_" + getProviderName(), 
					"garden_provider_" + getProviderName());
			ContentValues v = new ContentValues(3);
            v.put("provider", Long.valueOf(providerId));
            v.put("name", "icon");
            v.put("value", iconUri);
			context.getContentResolver().insert(ProviderSettings.CONTENT_URI, v);
		}
	}
	
 	protected abstract String getProviderName();
 	
 	protected abstract ContentValues getProviderValues();
 	
 	protected abstract Map<String, Object> getProviderSettings();
 	
 	protected abstract Bitmap getProviderTitleIcon();

}
